import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/Layout.vue'
import Home from '@/views/home/index.vue'
import TopCategory from '@/views/category/index.vue'
import SubCategory from '@/views/category/sub.vue'
import GoodsDetail from '@/views/goods/index.vue'
import Login from '@/views/login/index.vue'
import LoginCallback from '@/views/login/callback'
import Cart from '@/views/cart/index.vue'
import PayCheckout from '@/views/member/pay/checkout'

import store from '@/store'

// 路由映射规则
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home },
      { path: 'category/:id', component: TopCategory },
      { path: 'category/sub/:id', component: SubCategory },
      { path: 'product/:id', component: GoodsDetail }, // 二级分类页
      { path: 'cart', component: Cart },
      { path: '/member/checkout', component: PayCheckout }
    ]
  },
  { path: '/login', component: Login },
  { path: '/login/callback', component: LoginCallback }
]
// 使用APicreateRouter进行路由实例
const router = createRouter({
  history: createWebHashHistory(),
  routes,
  // 路由进阶 - 滚动行为

  scrollBehavior (to, from, savedPosition) {
    if (to.path !== '/') {
      return { top: 0 }
    }
  }
})
router.beforeEach((to, from, next) => {
  // 跳转去member开头的地址，却没有登录
  if (to.path.startsWith('/member') && !store.state.user.profile.token) {
    // 跳转到登录页，并传递
    next('/login?redirectUrl=' + to.fullPath)
  } else {
    next()
  }
})
// 导出路由实例
export default router
